< previous page page_296 next page >

Page 296
UNION Queries
Another powerful SQL clause is the UNION clause. This SQL keyword lets you create a union between two tables or SQL queries that contain similar, but unrelated, data. A UNION query is handy when you want to collate information from two queries into a single result set. Because UNION queries return nonupdateable result sets, they are good for producing on-screen displays, reports, and base data for generating graphs and charts.
For example, if you have a customer table and a vendor table, you might want to get a list of all vendors and customers who live in the state of Ohio. You could write an SQL statement to select the rows from the Customers table. Then write an SQL statement to select the rows from the Vendors table. Combine the two SQL statements into a single SQL phrase using the UNION keyword. Now you can get a single result set that contains the results of both queries.
In the following SQL statement (see Figure 8.31), you are creating a result set that contains all Publishers and Buyers located in the state of New York.
SELECT Name, City, StateProv, Zip FROM Publishers WHERE StateProv='NY'
   UNION
SELECT Name, City, StateProv, Zip FROM Buyers WHERE StateProv='NY'
   ORDER BY Zip
0296-01.jpg
Figure 8.31.
An example of a 
UNION query.
A note of caution when using the UNION query. To keep the same number of data columns, SQL does a data type override to insert results into columns that are not the same data types. The UNION query uses the column names of the first SQL query in the statement and creates a result set that displays the data even if data types must be altered to do so.
Each portion of the UNION query must have the same number of columns. If the first query results in six displayable columns, the query on the other side of the UNION statement must

 
< previous page page_296 next page >

If you like this book, buy it!